package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.github.gzuliyujiang.dialog.DialogConfig
import com.github.gzuliyujiang.dialog.DialogStyle
import com.github.gzuliyujiang.wheelpicker.DatimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.water.*
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.net.api.NormalApi24
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.net.observer.StatusLayoutObserver
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.UtilsBigDecimal.toDoubleWithTwoDecimalPlaces
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.widget.DividerItemDecoration
import com.two.screen.water.balance.widget.statueslayoutmanager.DefaultOnStatusChildClickListener
import com.two.screen.water.balance.widget.statueslayoutmanager.StatusLayoutManager
import kotlinx.android.synthetic.main.activity_order_server24.*
import java.math.BigDecimal
import java.util.*
import java.util.concurrent.TimeUnit

/*历史订单、本地订单*/
@Route(path = ARouterUtils.OrderServerActivity24)
class OrderServerActivity24 : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_order_server24
    lateinit var mSearchAdapter: SearchAdapter
    lateinit var mProductAdapter: ProductAdapter

    /*请求条件*/
    private var mDateBegin: String? = null
    private var mDateEnd: String? = null
    private var mStartEntity: DatimeEntity? = null
    private var mPage = 1 // 第几页
    private var mPageSize = 20 // 一页有几条
    private var mCurStatePay: Int? = 5 //支付状态  支付状态 0未支付 5 已支付
    private var mCurPayType: Int? = null //支付类型  支付类型 0 => '现金支付', 4 => '会员卡支付', 6 => '聚合支付',7 => '微会员支付'
    private var mSearchDay: Int? = null //说明： 快捷时间类型 1：今日、3：近3天、7近7天、30 近30天

    private var mStartPicker: DatimePicker? = null
    private var mEndPicker: DatimePicker? = null

    private var mIsClickCollected = true
    protected var mData: WaterOrderServerBean? = null

    /*加载订单列表*/
    val mOrderListLayoutManager: StatusLayoutManager by lazy {
        StatusLayoutManager.Builder(mOrderListLayout)
            .setLoadingLayout(R.layout.layout_status_layout_manager_loading)
            .setDefaultErrorClickViewVisible(setDefaultErrorClickViewVisible)
            .setDefaultEmptyClickViewVisible(setDefaultEmptyClickViewVisible)
            .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                override fun onEmptyChildClick(view: View?) {
                    getOrderList()
                }

                override fun onErrorChildClick(view: View?) {
                    getOrderList()
                }
            })
            .build()
    }

    /*加载订单详情*/
    val mRightRootLayoutManager: StatusLayoutManager by lazy {
        StatusLayoutManager.Builder(mRightRootLayout)
            .setLoadingLayout(R.layout.layout_status_layout_manager_loading)
            .setDefaultErrorClickViewVisible(setDefaultErrorClickViewVisible)
            .setDefaultEmptyClickViewVisible(setDefaultEmptyClickViewVisible)
            .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                override fun onEmptyChildClick(view: View?) {
                    getOrderDetails(mSearchAdapter.data.find { it.isLocalSelected })
                }

                override fun onErrorChildClick(view: View?) {
                    getOrderDetails(mSearchAdapter.data.find { it.isLocalSelected })
                }
            })
            .build()
    }

    override fun initView(savedInstanceState: Bundle?) {
        mOrderListLayoutManager.showSuccessLayout()
        mRightRootLayoutManager.showSuccessLayout()
    }

    private fun getOrderDetails(wob: WaterOrderServerBean?) {
        if (wob == null) return
        mRightRootLayoutManager.showLoadingLayout()
        NormalApi24.getOrderDetails(mIsClickCollected, wob?.id)
            .compose(RxUtils.aLifecycle(this@OrderServerActivity24))
            .subscribe(object : StatusLayoutObserver<WaterOrderServerBean>(this@OrderServerActivity24, mRightRootLayoutManager) {
                override fun onSuccessNext(t: BaseBean<out WaterOrderServerBean>) {
                    mRightRootLayoutManager.showSuccessLayout()
                    updateOrderInfo(t.data)
                }
            })
    }

    private fun getOrderList(isDialogLoading: Boolean = false) {
        if (!isDialogLoading) mOrderListLayoutManager.showLoadingLayout()
        if (isDialogLoading) mLoadingDialog.show()
        d("开始：${mDateBegin}，结束：${mDateEnd}")


        NormalApi24.getOrderList(mDateBegin, mDateEnd, mIsClickCollected, object : ApiCallBack() {
            @SuppressLint("SetTextI18n")
            override fun success(t: Any?) {
                super.success(t)
                if (!isDialogLoading) mOrderListLayoutManager.showSuccessLayout()
                if (isDialogLoading) mLoadingDialog.dismiss()

                var waterOrderBaseBean = t as WaterOrderBaseBean
                val rows = if (mIsClickCollected) waterOrderBaseBean.list?.rows else waterOrderBaseBean.rows
                rows?.firstOrNull()?.isLocalSelected = true
                mSearchAdapter.setNewData(rows)
                if (rows!!.isNotEmpty()) {

                    getOrderDetails(rows.firstOrNull())
                }

                mTotalPriceTv.text = "￥${t.stat?.sumOrderMoney}"
                mTotalServiceTv.text = "￥${t.stat?.sumMerchantServiceFee}"
                mRealIncomeTv.text = "￥${t.stat?.sumReceiveMoney}"

                mTotalCountTv.text = "（共 ${t.list?.total} 笔）"
            }

            override fun fail(t: Throwable) {
                if (!isDialogLoading) mOrderListLayoutManager.showErrorLayout()
                if (isDialogLoading) mLoadingDialog.dismiss()
                super.fail(t)
            }
        })
    }

    override fun initData() {
        initSearchRecyclerView()
        initProductRecyclerView()
    }

    @SuppressLint("ClickableViewAccessibility", "CheckResult", "SetTextI18n")
    override fun initListener() {
        mGoBackLayout.setOnClickListener { goBack() }
        mTodaySearchTv.setOnClickListener {
            updateSearchDayUI(mTodaySearchTv, 1)
        }
        mThreeDayTv.setOnClickListener {
            updateSearchDayUI(mThreeDayTv, 3)
        }
        mSevenSearchTv.setOnClickListener {
            updateSearchDayUI(mSevenSearchTv, 7)
        }
        mMonthSearchTv.setOnClickListener {
            updateSearchDayUI(mMonthSearchTv, 30)
        }
        mCollectHadTv.setOnClickListener {
            mCollectHadTv.isSelected = true
            mCollectNoneTv.isSelected = false
            mIsClickCollected = true
            mOrderTotalLayout.visibility = View.VISIBLE
            mDelOrderTv.visibility = View.GONE
            mPrintOrderTv.visibility = View.VISIBLE
            mCollectMoneyTv.visibility = View.GONE
            getOrderList()
        }
        mCollectNoneTv.setOnClickListener {
            mCollectNoneTv.isSelected = true
            mCollectHadTv.isSelected = false
            mIsClickCollected = false
            mOrderTotalLayout.visibility = View.GONE
            mDelOrderTv.visibility = View.VISIBLE
            mPrintOrderTv.visibility = View.GONE
            mCollectMoneyTv.visibility = View.VISIBLE
            getOrderList()
        }
        mCollectHadTv.performClick()
        mResetFilterTv.setOnClickListener {
            //重置筛选条件
            mPage = 0 //从
            mDateBegin = null
            mDateEnd = null
            mStartEntity = null
            mSearchDay = null
            mCurStatePay = null//支付状态
            mCurPayType = null//支付类型
            mStartTimeTv.text = "开始时间"
            mEndTimeTv.text = "结束时间"
            setSearchTvFalse()
        }
        RxView.clicks(mStartTimeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                DialogConfig.setDialogStyle(DialogStyle.Three)
                if (mStartPicker == null) {
                    mStartPicker = DatimePicker(this)
                    val wheelLayout = mStartPicker!!.wheelLayout
                    mStartPicker!!.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        mDateBegin = "$year-${String.format("%02d", month)}-${String.format("%02d", day)} ${String.format("%02d", hour)}:${String.format("%02d", minute)}:${String.format("%02d", second)}"
                        mStartTimeTv.text = mDateBegin
                        var startCalendar = Calendar.getInstance()
                        startCalendar.set(year, month - 1, day, hour, minute, second)
                        mStartEntity = DatimeEntity().apply {
                            date = DateEntity.target(startCalendar)
                        }
                        mEndTimeTv.text = "结束时间"
                        mDateEnd = null
                        mEndPicker = null
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    val target = DateEntity.target(2023, 1, 1)
                    val datimeEntity = DatimeEntity()
                    datimeEntity.date = target
                    wheelLayout.setRange(datimeEntity, DatimeEntity.now()) //设置选择时间范围
                    wheelLayout.setDefaultValue(DatimeEntity.now()) //设置默认当选时间
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                }
                mStartPicker?.show()
                mStartPicker?.let { DialogUtil.hideNavigationBar(it.window) }
            }
        RxView.clicks(mEndTimeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                DialogConfig.setDialogStyle(DialogStyle.Three)
                if (mDateBegin == null) {
                    ToastUtil.showToast("请选择开始时间")
                    return@subscribe
                }
                if (mEndPicker == null) {
                    mEndPicker = DatimePicker(this)
                    val wheelLayout = mEndPicker!!.wheelLayout
                    mEndPicker!!.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        mDateEnd = "$year-${String.format("%02d", month)}-${String.format("%02d", day)} ${String.format("%02d", hour)}:${String.format("%02d", minute)}:${String.format("%02d", second)}"
                        mEndTimeTv.text = mDateEnd
                        var t1 = CommUtils.YMD2s(mDateEnd, "yyyy-MM-dd HH:mm:ss") ?: 0L
                        var t2 = CommUtils.YMD2s(mDateBegin, "yyyy-MM-dd HH:mm:ss") ?: 0L
                        if (t1 < t2) { //结束时间 < 开始时间 位置互换。
                            var temp = mDateBegin
                            mDateBegin = mDateEnd
                            mDateEnd = temp
                            mStartTimeTv.text = mDateBegin
                            mEndTimeTv.text = mDateEnd
                        }
                        //去掉选中快捷键1、3、7、30
                        mSearchDay = null
                        setSearchTvFalse()
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    wheelLayout.setRange(mStartEntity, DatimeEntity.now()) //设置选择时间范围
                    wheelLayout.setDefaultValue(DatimeEntity.now()) //设置默认当选时间
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                }
                mEndPicker?.show()
                mEndPicker?.let { DialogUtil.hideNavigationBar(it.window) }
            }
        RxView.clicks(mFilterSearchTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (mDateBegin != null && mDateEnd == null) {
                    ToastUtil.showToast("请选择结束时间!")
                    return@subscribe
                }
                getOrderList(true)
            }

        RxView.clicks(mGoBackLayout)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe { finish() }
        RxView.clicks(mPrintOrderTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe { ToastUtil.showToast("等待打印模板出来再打印") }
        RxView.clicks(mDelOrderTv)//删除
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                android.app.AlertDialog.Builder(this@OrderServerActivity24)
                    .setMessage("是否删除？")
                    .setCancelable(false)
                    .setPositiveButton("确认") { dialog, _ ->
                        delHangOrderClick()
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                    .show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        RxView.clicks(mCollectMoneyTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                go2IndexForCollect()
            }
    }

    /*删除挂单*/
    private fun delHangOrderClick() {
        val find = mSearchAdapter.data.find { it.isLocalSelected }
        if (find == null) {
            ToastUtil.showToast("请选择订单!")
            return
        }
        NormalApi24.delProductHang(find.id)
            .compose(RxUtils.aLifecycle(this@OrderServerActivity24))
            .subscribe(object : DialogObserver<NormalResultBean>(this@OrderServerActivity24) {
                override fun dataIsNull(t: BaseBean<out NormalResultBean>) {
                    onSuccessNext(t)
                }

                override fun onSuccessNext(t: BaseBean<out NormalResultBean>) {
                    getOrderList()
                }
            })
    }

    /*回到主秤准备结算*/
    private fun go2IndexForCollect() {
        val find = mSearchAdapter.data.find { it.isLocalSelected }
        if (find == null) {
            ToastUtil.showToast("请选择订单!")
            return
        }

        if (mProductAdapter.data.isEmpty()) {
            ToastUtil.showToast("订单商品为空!")
            return
        }
        var newProductList = mProductAdapter.data.map {
            ProductBean().apply {
                this.productName = it.productName
                this.productUnitPrice = it.unitPrice
                this.id = it.productId
                this.hangId = find.id
                this.batchId = it.productBatchId
                this.productImage = null
                this.status = 0
                this.productSpecs = it.productSpecs
                this.deliveryTime
                this.supplierName = it.supplierName


                this.roughWeight = try {
                    it.quantity?.toDouble() ?: 0.0//毛重
                } catch (e: Exception) {
                    0.0
                }
                this.peelWeight = try {
                    it.skinWeight?.toDouble() ?: 0.0//皮重
                } catch (e: Exception) {
                    0.0
                }
                this.netWeight = try {
                    it.grossWeight?.toDouble() ?: 0.0//净重
                } catch (e: Exception) {
                    0.0
                }
                this.subTotalPrice = try {
                    var subTotal = this.netWeight * (this.productUnitPrice?.toDouble() ?: 0.0)
                    subTotal.toString().toDoubleWithTwoDecimalPlaces()//小计
                } catch (e: Exception) {
                    0.0
                }
            }
        }
        EventBusUtil.sendEvent(Event(EventCode.HANG_GO_COLLECT, newProductList))
        finish()
    }

    private fun updateSearchDayUI(searchTv: TextView, day: Int) {
        setSearchTvFalse()
        searchTv.isSelected = mSearchDay != day
        mSearchDay = if (searchTv.isSelected) day else null

        if (mSearchDay != null) {
            var start = CommUtils.toYMD_HMS(CommUtils.YMD2s(CommUtils.toYMD(System.currentTimeMillis() / 1000 - (day - 1) * 3600 * 24 + 60)))
            var end = CommUtils.toYMD_HMS(System.currentTimeMillis() / 1000)
            mDateBegin = start
            mDateEnd = end
            mStartTimeTv.text = mDateBegin
            mEndTimeTv.text = mDateEnd
        } else {
            mDateBegin = null
            mDateEnd = null
            mStartTimeTv.text = "开始时间"
            mEndTimeTv.text = "结束时间"
        }
    }

    private fun setSearchTvFalse() {
        mTodaySearchTv.isSelected = false
        mThreeDayTv.isSelected = false
        mSevenSearchTv.isSelected = false
        mMonthSearchTv.isSelected = false
    }


    private fun setData(isRefresh: Boolean, data: MutableList<WaterOrderServerBean>?) {
        mPage++
        val size = data?.size
            ?: 0
        if (isRefresh) {
            mSearchAdapter.setNewData(data)
        } else {
            if (size > 0) {
                mSearchAdapter.addData(data!!)
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mSearchAdapter.loadMoreEnd(isRefresh)
        } else {
            mSearchAdapter.loadMoreComplete()
        }
    }

    private fun initSearchRecyclerView() {
        (mSearchRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mSearchRecyclerView?.addItemDecoration(
            DividerItemDecoration(
                this, DividerItemDecoration.HORIZONTAL_LIST,
                resources.getDimension(R.dimen.common_measure_1dp).toInt(),
                ContextCompat.getColor(App.context!!, R.color.c6), true
            )
        )
        mSearchAdapter = SearchAdapter()
        mSearchRecyclerView.layoutManager = LinearLayoutManager(this)
        mSearchRecyclerView.adapter = mSearchAdapter
        mSearchAdapter.bindToRecyclerView(mSearchRecyclerView)
        mSearchAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    private fun initProductRecyclerView() {
        (mProductRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mProductAdapter = ProductAdapter()
        mProductRecyclerView.layoutManager = LinearLayoutManager(this)
        mProductRecyclerView.adapter = mProductAdapter
        mProductAdapter.bindToRecyclerView(mProductRecyclerView)
        mProductAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    /*搜索列表 适配器*/
    inner class SearchAdapter : BaseQuickAdapter<WaterOrderServerBean, BaseViewHolder>(R.layout.item_order_server_search_selected24, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: WaterOrderServerBean) {
            helper.getView<TextView>(R.id.item_tv1).apply {
                isSelected = item.isLocalSelected
                text = item.code
            }
            helper.getView<TextView>(R.id.item_tv2).apply {
                isSelected = item.isLocalSelected
                text = item.totalProductMoney
            }
            helper.getView<TextView>(R.id.item_tv3).apply {
                isSelected = item.isLocalSelected
                text = item.createTime
            }
            helper.getView<View>(R.id.item_root_view).apply {
                isSelected = item.isLocalSelected
                setOnClickListener {
                    mData.forEach { it.isLocalSelected = false }
                    val waterOrderServerBean = mData[helper.bindingAdapterPosition]
                    waterOrderServerBean.isLocalSelected = true
                    notifyDataSetChanged()
                    getOrderDetails(waterOrderServerBean)
                }
            }
        }
    }

    /*商品列表 适配器*/
    inner class ProductAdapter : BaseQuickAdapter<WaterOrderServerBean, BaseViewHolder>(R.layout.item_order_server_product24, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: WaterOrderServerBean) {
            helper
                .setText(R.id.item_tv1, (helper.bindingAdapterPosition + 1).toString())
                .setText(R.id.item_tv2, item.productName)
                .setText(R.id.item_tv3, item.productSpecs.toString())
                .setText(R.id.item_tv4, item.status)
                .setText(R.id.item_tv5, item.unitPrice)
                .setText(R.id.item_tv6, item.quantity)
                .setText(R.id.item_tv7, item.money)
                .setText(R.id.item_tv8, item.skinWeight)
                .setText(R.id.item_tv9, item.grossWeight)
                .getView<View>(R.id.item_root_view).apply {
                    setBackgroundColor(if (helper.bindingAdapterPosition % 2 == 0) CommUtils.getColor(R.color.f6) else CommUtils.getColor(R.color.white_f1f1f1))
                }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderInfo(orderServerBean: WaterOrderServerBean?) {
        mProductAdapter.setNewData(orderServerBean?.detailList)
        mOrderSnTv.text = orderServerBean?.code
        mOrderCreateTimeTv.text = orderServerBean?.receiveMoneyTime
        mOrderOperationUserTv.text = orderServerBean?.receiveMoneyBy

        var totalNetWeight = BigDecimal(0.0)
        orderServerBean?.detailList?.forEach {
            totalNetWeight = try {
                UtilsBigDecimal.add(totalNetWeight, it.weight)
            } catch (e: Exception) {
                ToastUtil.showToast("计算总净重异常:$e")
                BigDecimal(0.0)
            }
        }
        //买家费率  费用/realPay
        var buyRate = try {
            (orderServerBean?.buyerServiceFee?.toDouble() ?: 0.0) / (orderServerBean?.orderMoney?.toDouble() ?: 0.0) * 100
        } catch (e: Exception) {
            0
        }
        var sellerRate = try {
            (orderServerBean?.merchantServiceFee?.toDouble() ?: 0.0) / (orderServerBean?.orderMoney?.toDouble() ?: 0.0) * 100
        } catch (e: Exception) {
            0
        }


        var sunInfo = "商品总额：￥${orderServerBean?.totalProductMoney}　　总重量：${String.format("%.2f", totalNetWeight)}　　优惠金额：￥${orderServerBean?.discountMoney}　　订单总额：￥${orderServerBean?.orderMoney}" +
                "" +
                "\n买家服务费(${buyRate}%)：￥${orderServerBean?.buyerServiceFee}　　卖家服务费(${sellerRate}%)：￥${orderServerBean?.merchantServiceFee}"
        mOrderSunInfoTv.text = sunInfo


        var payInfo = "支付方式：${PayTypeBean.getPayTypeName(orderServerBean?.payType)}　　买家应付：￥${orderServerBean?.payMoney}　　卖家实收：￥${
            UtilsBigDecimal.sub(
                orderServerBean?.orderMoney?.toDouble() ?: 0.0,
                orderServerBean?.merchantServiceFee?.toDouble() ?: 0.0
            )
        }　　"
        mOrderPayInfoTv.text = payInfo

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.device?.name?.contains("USB", true) != true) return false
        if (event.action == KeyEvent.ACTION_DOWN) {//处理触发两次
            when (keyCode) {
                33 -> { //d("帐户/E")
                    mGoBackLayout.performClick()
                    EventBusUtil.sendEvent(Event(EventCode.FINISH_FUNCTION_MENU_ACTIVITY))
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}